package zsj.androidknife.ThreadPool;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;

import zsj.androidknife.R;
import zsj.androidknife.utils.BackgroundAction;
import zsj.androidknife.utils.SimpleBackgroundAction;
import zsj.androidknife.utils.SimpleUiAction;
import zsj.androidknife.utils.UiAction;

/**
 * Created by zsj on 2016/4/20 0020.
 *
 */
public class TaskExecutor {
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());

    private TaskExecutor() {
    }
    private static class InstanceHolder {
        private static TaskExecutor INSTANCE = new TaskExecutor();

    }

    public static TaskExecutor getInstance() {
        return InstanceHolder.INSTANCE;
    }

    /**
     * 执行一个后台任务,没有输入参数,没有后续UI动作
     * @param backgroundAction
     */
    public void submitBackground(BackgroundAction backgroundAction)
    {
        submitBackground(backgroundAction, null);
    }

    /**
     * 执行一个后台任务,有输入参数,没有后续UI动作
     * @param backgroundAction
     * @param param
     * @param <P>
     * @param <R>
     */
    public <P,R> void submitBackground(BackgroundAction<P,R> backgroundAction,P param)
    {
        submitBackgroundForResult(backgroundAction,null,param);
    }

    /**
     * 执行一个后台任务,有输入参数,有后续UI动作
     * @param backgroundAction
     * @param uiAction
     * @param param
     * @param <P>
     * @param <R>
     */
    public <P,R> void submitBackgroundForResult(BackgroundAction<P,R> backgroundAction,UiAction<R> uiAction,P param)
    {
        ExecutorService exec = ThreadPool.getThreadPool();
        Runnable task = TaskFactory.getBgAndUiTask(mainHandler,backgroundAction,uiAction,param);
        exec.submit(task);
    }

    /**
     * 只是执行一个UI操作,有泛型输入参数
     * @param uiAction
     * @param param
     * @param <T>
     */
    public <T> void submitUiAction(UiAction<T> uiAction,T param)
    {
        mainHandler.post(TaskFactory.getRunnable(uiAction, param));
    }

    /**
     * 执行一个UI操作,没有输入参数
     * @param uiAction
     */
    public void submitUiAction(UiAction uiAction)
    {
        submitUiAction(uiAction,null);
    }

    /**
     * 执行一个简单的后台操作和简单UI操作
     * UI操作会在后台操作执行完毕之后被调用
     * @param backgroundAction
     * @param uiAction
     */
    public void submitBackgroundForResult(SimpleBackgroundAction backgroundAction,SimpleUiAction uiAction)
    {
        ExecutorService exec = ThreadPool.getThreadPool();
        Runnable task = TaskFactory.getBgAndUiTask(mainHandler,backgroundAction,uiAction);
        exec.submit(task);
    }
}
